// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
	/**
	 * getData方法描述
	 * @param {string} category_id 关联分类id
	 * @returns {object} 返回值描述
	 */
	async getData(category_id = '') {
		try {
			const db = uniCloud.databaseForJQL({
				clientInfo: this.getClientInfo()
			})
			const {
				data
			} = await db.collection('opendb-mall-goods').where({
				category_id
			}).get()

			return {
				data
			}
		} catch (err) {
			return {
				errCode: 'ERROR',
				errMsg: '错误',
				errInfo: err
			}
		}
	},
	/**
	 * getGoodsData方法描述
	 * @param {string} _id 数据id
	 * @returns {object} 返回值描述
	 */
	async getGoodsData(_id = '') {
		try {
			const db = uniCloud.databaseForJQL({
				clientInfo: this.getClientInfo()
			})

			return await db.collection('opendb-mall-goods').where({
				_id
			}).get({
				getOne: true
			})
		} catch (err) {
			return {
				errCode: 'ERROR',
				errMsg: '错误',
				errInfo: err
			}
		}
	},
	/**
	 * addData方法描述
	 * @param {object} params 传参
	 */
	async addData(params) {
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		try {
			const db = uniCloud.databaseForJQL({
				clientInfo: this.getClientInfo()
			})
			return await db.collection('opendb-mall-goods').add(params)
		} catch (err) {
			return {
				errCode: 'ERROR',
				errMsg: '错误',
				errInfo: err
			}
		}
	},
	/**
	 * updateData方法描述
	 * @param {object} params 传参
	 */
	async updateData(params) {
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		const {
			_id,
			data
		} = params || {}
		if (!_id) {
			return {
				errCode: 'ID_IS_NULL',
				errMsg: '_id不能为空'
			}
		}
		try {
			const db = uniCloud.database()
			return await db.collection('opendb-mall-goods').doc(
				_id
			).set(data)
		} catch (err) {
			return {
				errCode: 'ERROR',
				errMsg: '错误',
				errInfo: err
			}
		}
	},
	/**
	 * deleteData方法描述
	 * @param {string} _id 数据id
	 */
	async deleteData(_id) {
		if (!_id) {
			return {
				errCode: 'ID_IS_NULL',
				errMsg: '_id不能为空'
			}
		}
		try {
			const db = uniCloud.databaseForJQL({
				clientInfo: this.getClientInfo()
			})
			return await db.collection('opendb-mall-goods').where({
				_id
			}).remove()
		} catch (err) {
			return {
				errCode: 'ERROR',
				errMsg: '错误',
				errInfo: err
			}
		}
	}
}